package com.ocom.accesservice.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.accesservice.service.MjYkmService;
import com.ocom.accesservice.service.PersonnelInfoService;
import com.ocom.accesservice.service.PersonnelYkmService;
import com.ocom.accesservice.vo.PersonnelListVo;
import com.ocom.accesservice.vo.PersonnelYkmVo;
import com.ocom.accesservice.vo.YkmSumListVo;
import com.ocom.accesservice.vo.devicelogin.GetYkmPersonnelListVo;
import com.ocom.accesservice.vo.devicelogin.YkmSumListRVo;
import com.ocom.common.constant.AccessServiceUrl;
import com.ocom.common.entity.access.EntityPersonnelYkm;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.*;


@RestController
public class LargeScreenController {
    private final Logger log = LoggerFactory.getLogger(LargeScreenController.class);

    @Autowired
    private MjYkmService mjYkmService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private PersonnelYkmService personnelYkmService;

    /**
     * 健康码人数（LargeScreen/getYkmNums）
     */
    @GetMapping(AccessServiceUrl.URL_LargeScreenGetYkmNums)
    public Result LargeScreenGetYkmNums(Long comId) {
        if (comId == null) {
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203, "单位编号为空");
        }
        Integer gnums = 0;
        Integer rnums = 0;
        Integer ynums = 0;
        Integer other = 0;
        Integer total = 0;
        Map<String, Object> map = new HashMap<>();
        List<EntityPersonnelInfo> personInfo = null;
        try {
            //查询人员信息表personnel_info，获取单位下人员信息（comId、pId）
            personInfo = personnelInfoService.getPersonInfo(comId);
            if (personInfo.size() == 0) {
                map.put("red",0);
                map.put("yellow",0);
                map.put("green",0);
                map.put("other",0);
                map.put("total",0);
                return ResultUtil.success(map);
            }
        } catch (Exception exception) {
            log.error("查询人员信息失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_203, "查询人员信息失败");
        }


        try {
            //根据人员信息的comId+pId查询防疫监控信息表 personnel_ykm，获取单位下人员防疫信息（codeColor），
            // 获取不到防疫信息默认color=0;

            for (EntityPersonnelInfo personnelInfo: personInfo) {

                EntityPersonnelYkm entityPersonnelYkm = personnelYkmService.GetPersonnelYkm(personnelInfo.getComId(), personnelInfo.getPId());
                if (entityPersonnelYkm != null){
                    if (entityPersonnelYkm.getCodeColor().equals("红")){
                        rnums++;
                    }else if (entityPersonnelYkm.getCodeColor().equals("黄")){
                        ynums++;
                    }else if (entityPersonnelYkm.getCodeColor().equals("绿")){
                        gnums++;
                    }
                }else {
                    other++;
                }
            }
            total = rnums + ynums + gnums + other;
            map.put("red",rnums);
            map.put("yellow",ynums);
            map.put("green",gnums);
            map.put("other",other);
            map.put("total",total);
        }catch (Exception exception){
            log.error("查询防疫监控信息表失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"查询防疫监控信息表失败");
        }
        return ResultUtil.success(map);

    }

    /**
     * 核酸检测归类统计（LargeScreen/getYkmSumByHS）
     * */
    @GetMapping(AccessServiceUrl.URL_LargeScreenGetYkmSumByHS)
    public Result LargeScreenGetYkmSumByHS(Long comId){
        if (comId == null) {
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203, "单位编号为空");
        }
        Integer hours24 = 0;
        Integer hours48 = 0;
        Integer hours72 = 0;
        Integer within7Days = 0;
        Integer noNucleic = 0;
        Integer positive = 0;
        Map<String, Object> map = new HashMap<>();

        List<EntityPersonnelInfo> personInfo = null;
        try {
            //查询人员信息表personnel_info，获取单位下人员信息（comId、pId）
            personInfo = personnelInfoService.getPersonInfo(comId);
            if (personInfo.size() == 0) {
                map.put("hours24",0);
                map.put("hours48",0);
                map.put("hours72",0);
                map.put("within7Days",0);
                map.put("noNucleic",0);
                map.put("positive",0);
                return ResultUtil.success(map);
            }
        } catch (Exception exception) {
            log.error("查询人员信息失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_203, "查询人员信息失败");
        }

        try {
            //根据人员信息的comId+pId查询防疫监控信息表 personnel_ykm，获取单位下人员防疫信息（codeColor），
            // 获取不到防疫信息默认color=0;

            for (EntityPersonnelInfo personnelInfo: personInfo) {

                EntityPersonnelYkm entityPersonnelYkm = personnelYkmService.GetPersonnelYkm(personnelInfo.getComId(), personnelInfo.getPId());
                if (entityPersonnelYkm == null){
                    noNucleic++;
                }
                else {
                    if (entityPersonnelYkm.getHsResult().equals("阳性")){
                        positive++;
                    }
                    Integer hours = getHours(entityPersonnelYkm.getHsTime());

                    if(hours<=24){
                        hours24++;
                        continue;
                    }
                    if(hours<=48){
                        hours48++;
                        continue;
                    }
                    if(hours<=72){
                        hours72++;
                        continue;
                    }
                    if(hours<=168){
                        within7Days++;
                    }

                }
            }
            map.put("hours24",hours24);
            map.put("hours48",hours48);
            map.put("hours72",hours72);
            map.put("within7Days",within7Days);
            map.put("noNucleic",noNucleic);
            map.put("positive",positive);
        }catch (Exception exception){
            log.error("查询防疫监控信息表失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"查询防疫监控信息表失败");
        }
        return ResultUtil.success(map);
    }



    public static Integer getHours(Date date) throws ParseException {
        Long from = date.getTime();
        Long to = new Date().getTime();
        return Math.toIntExact(((to - from) / (1000 * 60 * 60)));
    }

    /**
     * 疫苗接种归类统计（LargeScreen/getYkmSumByYM）
     * */
    @GetMapping(AccessServiceUrl.URL_LargeScreenGetYkmSumByYM)
    public Result LargeScreenGetYkmSumByYM(Long comId){
        if (comId == null) {
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203, "单位编号为空");
        }
        Integer ym1 = 0;
        Integer ym2 = 0;
        Integer ym3 = 0;
        Integer noYm = 0;
        Map<String, Object> map = new HashMap<>();
        List<EntityPersonnelInfo> personInfo = null;
        try {
            //查询人员信息表personnel_info，获取单位下人员信息（comId、pId）
            personInfo = personnelInfoService.getPersonInfo(comId);
            if (personInfo.size() == 0) {
                map.put("ym1",0);
                map.put("ym2",0);
                map.put("ym3",0);
                map.put("noYm",0);
                return ResultUtil.success(map);
            }
        } catch (Exception exception) {
            log.error("查询人员信息失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_203, "查询人员信息失败");
        }

        try {
            //根据人员信息的comId+pId查询防疫监控信息表 personnel_ykm，获取单位下人员防疫信息（codeColor），
            // 获取不到防疫信息默认color=0;

            for (EntityPersonnelInfo personnelInfo: personInfo) {

                EntityPersonnelYkm entityPersonnelYkm = personnelYkmService.GetPersonnelYkm(personnelInfo.getComId(), personnelInfo.getPId());
                if (entityPersonnelYkm == null){
                    noYm++;
                }
                if (entityPersonnelYkm != null){
                    if (entityPersonnelYkm.getYmNum() == 1) {
                        ym1++;
                    }
                    if (entityPersonnelYkm.getYmNum() == 2) {
                        ym2++;
                    }
                    if (entityPersonnelYkm.getYmNum() == 3) {
                        ym3++;
                    }
                    if (entityPersonnelYkm.getYmNum() == null) {
                        noYm++;
                    }
                }
            }
            map.put("ym1",ym1);
            map.put("ym2",ym2);
            map.put("ym3",ym3);
            map.put("noYm",noYm);
        }catch (Exception exception){
            log.error("查询防疫监控信息表失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"查询防疫监控信息表失败");
        }
        return ResultUtil.success(map);
    }

    /**
     * 防疫人员列表（getYkmPersonnelList）
     * */
    @PostMapping(AccessServiceUrl.URL_GetYkmPersonnelList)
    public Result GetYkmPersonnelList(@Validated @RequestBody PersonnelListVo personnelListVo){
        if (personnelListVo.getComId()==null){
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203,"单位编号为空");
        }

        if (personnelListVo.getPage() == null){
            log.error("页码page为空");
            return ResultUtil.error(ResultEnum.Err_203,"页码page为空");
        }
        if (personnelListVo.getSize() == null){
            log.error("页数size为空");
            return ResultUtil.error(ResultEnum.Err_203,"页数size为空");
        }
        Map<String, Object> map = new HashMap<>();
        try {
            List<Integer> deptIdsList = new ArrayList<>();
            if (personnelListVo.getDeptIds() != null){
                String[] deptIdsArr = personnelListVo.getDeptIds().split(",");
                for (String deptId: deptIdsArr) {
                    deptIdsList.add(Integer.valueOf(deptId));
                }
            }
            PageHelper.startPage(personnelListVo.getPage(),personnelListVo.getSize());
            List<GetYkmPersonnelListVo> getYkmPersonnelListVos = personnelYkmService.GetYkmPersonnelList(personnelListVo.getComId(), deptIdsList,
                    personnelListVo.getPCode(), personnelListVo.getPName(),personnelListVo.getCodeColor(),personnelListVo.getHsResult());
            PageInfo<GetYkmPersonnelListVo> getYkmPersonnelListVoPageInfo = new PageInfo<>(getYkmPersonnelListVos);
            map.put("total",getYkmPersonnelListVoPageInfo.getTotal());
            map.put("list",getYkmPersonnelListVos);
        }catch (Exception exception){
            log.error("查询防疫人员列表失败：{{}}",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"查询防疫人员列表失败");
        }
        log.info("返回值map{{}}",map);
        return ResultUtil.success(map);
    }

    /**
     * 防疫汇总指标列表详情（getYkmSumList）
     * */
    @PostMapping(AccessServiceUrl.URL_getYkmSumList)
    public Result getYkmSumList(@Validated @RequestBody YkmSumListVo ykmSumListVo){
        log.info("ykmSumListVo{{}}",ykmSumListVo);
        if (ykmSumListVo.getComId()==null){
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203,"单位编号为空");
        }
        if (ykmSumListVo.getPage() == null){
            log.error("页码page为空");
            return ResultUtil.error(ResultEnum.Err_203,"页码page为空");
        }
        if (ykmSumListVo.getSize() == null){
            log.error("页数size为空");
            return ResultUtil.error(ResultEnum.Err_203,"页数size为空");
        }

        Map<String, Object> map = new HashMap<>();
        try {

            PageHelper.startPage(ykmSumListVo.getPage(),ykmSumListVo.getSize());
            List<YkmSumListRVo> ykmSumList = personnelYkmService.getYkmSumList(ykmSumListVo.getComId(), ykmSumListVo);

            PageInfo<YkmSumListRVo> ykmSumListRVoPageInfo = new PageInfo<>(ykmSumList);
            map.put("total",ykmSumListRVoPageInfo.getTotal());
            map.put("list",ykmSumList);
        }catch (Exception exception){
            log.error("防疫汇总指标列表详情失败：{{}}",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"防疫汇总指标列表详情失败");
        }
        log.info("返回值map{{}}",map);
        return ResultUtil.success(map);
    }

}